package com.lckj.android.shell.module.web;

import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.lckj.android.shell.R;
import com.lckj.android.shell.base.BaseActivity;
import com.lckj.android.shell.ui.widget.ProgressView;

/**
 * @author lc. 2023-10-22 15:18
 */
public class WebActivity extends BaseActivity {

    private static final String EXTRA_TITLE = "extra.title";
    private static final String EXTRA_URL = "extra.url";

    private String mInitUrl;
    private String mTitle;
    private WebJsInterface mWebJsInterface;

    private ViewGroup mToolbarLayout;
    private AppCompatImageView mToolbarNav;
    private TextView mToolbarTitle;
    private AppCompatImageView mToolbarMenu;
    private WebView mWebView;
    private ProgressView mProgressView;

    public static void open(Context context, String title, String url) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(EXTRA_TITLE, title);
        intent.putExtra(EXTRA_URL, url);
        if (!(context instanceof WebActivity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.module_web_activity);
        initData();
        initView();
    }

    private void initData() {
        mWebJsInterface = new WebJsInterface(this);
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        mTitle = intent.getStringExtra(EXTRA_TITLE);
        mInitUrl = intent.getStringExtra(EXTRA_URL);
    }

    private void initView() {
        mToolbarLayout = findViewById(R.id.ly_toolbar);
        mToolbarNav = findViewById(R.id.iv_toolbar_back);
        mToolbarTitle = findViewById(R.id.tv_toolbar_title);
        mToolbarMenu = findViewById(R.id.iv_toolbar_menu);
        mWebView = findViewById(R.id.web_view);
        mProgressView = findViewById(R.id.load_progress_view);

        mToolbarNav.setImageResource(R.drawable.icon_toolbar_back_dark);
        mToolbarNav.setOnClickListener(view -> onBackPressed());
        mProgressView.setColor(getResources().getColor(R.color.progress_bg_accent),
                getResources().getColor(R.color.progress_color_accent));
        mWebView.setWebViewClient(new CustomWebViewClient());
        mWebView.setWebChromeClient(new CustomChromeClient());

        // web view settings
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);
        // 如果访问的页面中要与 Javascript 交互，则 webView 必须设置支持 Javascript
        webSettings.setJavaScriptEnabled(true);
        // 支持通过 JS 打开新窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        // 设置自适应屏幕，两者合用
        // 将图片调整到适合 webView 的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);

        // 缩放操作
        // 支持缩放，默认为true。是下面那个的前提。
        webSettings.setSupportZoom(true);
        // 设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setBuiltInZoomControls(true);
        // 隐藏原生的缩放控件
        webSettings.setDisplayZoomControls(false);

        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        // 支持自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        // 设置编码格式
        webSettings.setDefaultTextEncodingName("utf-8");
        // 字体大小不跟随系统
        webSettings.setTextZoom(100);

        // 5.0 开始 webView https 当中不能加载http资源，需要设置开启
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // 开启第三方cookie支持
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
        }

        mWebView.addJavascriptInterface(mWebJsInterface, "NativeSdk");
        mWebView.loadUrl(mInitUrl);
    }

    /*** 调用 JS 方法 */
    public void callJsMethod(String methodName) {
        if (isFinishing() || isDestroyed() || mWebView == null) {
            return;
        }
        mWebView.loadUrl("javascript:" + methodName);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mWebView == null) {
            super.onBackPressed();
            return;
        }
        // 回退到上一个页面
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    ///////////////////////////////////////////////////////////////////////////
    // inner class
    ///////////////////////////////////////////////////////////////////////////

    private static class CustomWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    }

    private class CustomChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            WebBackForwardList backForwardList = view.copyBackForwardList();
            if (backForwardList == null) {
                return;
            }
            WebHistoryItem currentItem = backForwardList.getCurrentItem();
            if (currentItem == null) {
                return;
            }
            String titleCur = currentItem.getTitle();
            mToolbarTitle.setText(TextUtils.isEmpty(titleCur) ? "" : titleCur);
        }

        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
            finish();
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            mProgressView.setProgress(newProgress);
        }
    }

}
